import React from 'react';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';
import { withRouter, Route } from 'react-router-dom';
import { Tools, Icon, Modal, Button, Bubble } from 'weaver-mobile';
import { RouteLayout, ListEditable } from 'weaver-mobile-page';
import New from './new'
import Detail from './detail'
import { WrCardList, WrAlertPage, WrRemark } from '../../../public'
import { Empty, PlanCard, EmptyAddButton } from "../coms";
const getLabel = Tools.getLabel;
const alert = Modal.alert;
@inject('planViewStore')
@withRouter
@observer
class Summary extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      remarkInitText: ''
    };
    this.store = this.props.planViewStore;
  }


  render() {
    const prefixClass = 'workrelate-mobile-plan-planview-share-';
    let { planmap, summarymap, summaryout, summaryin, planlist, detailLayoutStore, newLayoutStore, canedit, listEditableStore, planListStore, summaryInStore, summaryOutStore, summaryConditions, setState, remark, remarkStore, remarkLayout } = this.store;
    return (
      <div >
        <div className="workrelate-mobile-plan-planview-planin">

          <WrCardList
            title={getLabel('509032', '计划内')}
            dataMapList={summarymap.list ? summarymap.list : []}
            dataList={toJS(summaryin)}
            showAdd={false}
            showDelete={false}
            showCheckBox={false}
            // emptyComponent={<WrAlertPage icon="view" show={true} msg='暂无'></WrAlertPage>}
            emptyComponent={<Empty title={getLabel(83553, '暂无数据')} ></Empty>}
            dropList={this.getSummaryInDropList()}
            onRowClick={(record, index) => {
              this.onRowClick(record, index, true)
            }}
          />
          <WrCardList
            title={getLabel('509034', '计划外')}
            showAdd={canedit}
            showDelete={canedit}
            showCheckBox={canedit}
            dataMapList={summarymap.list ? summarymap.list : []}
            dataList={toJS(summaryout)}
            onAdd={this.onAdd}
            onDelete={this.onSummaryOutDelete}
            emptyComponent={<Empty title={getLabel(83553, '暂无数据')} ></Empty>}
            dropList={this.getSummaryOutDropList()}
            onRowClick={this.onRowClick}
          />
          <WrCardList
            // showContent={false}
            title={getLabel(25734,'说明')}
            dataMapList={[]}
            dataList={[]}
            showAdd={false}
            showDelete={false}
            showCheckBox={false}
            emptyComponent={(remark == '' && !canedit) ? <Empty title={getLabel(83553, '暂无数据')}></Empty> : <WrRemark
              remark={remark}
              remarkStore={remarkStore}
              remarkLayoutStore={remarkLayout}
              iconClick={() => {
                //this.store.recordIndexScrollHeight()
                this.setState({ remarkInitText: remark })
                this.props.history.push(remarkLayout.path)
              }}
              onTextChange={(e) => {
                this.store.remark = e
              }}
              onOk={() => this.props.history.push("/planHome/planView/index")}
              onCancel={() => {
                this.store.remark = this.state.remarkInitText
                this.props.history.push("/planHome/planView/index")
              }}
              editable={canedit}
            ></WrRemark>}
          />

        </div>
      </div>
    );
  }

  //把对象转成 a=b&c=2的格式
  transObj2Url = (obj) => {
    if (obj) {
      let urlStr = ''
      Object.keys(obj).map(k => {
        if (k && obj[k] != '') {
          urlStr += k + "=" + obj[k] + "&"
        }
      })
      return urlStr
    } else {
      return ''
    }
  }
  onRowClick = (record, index, isPlanIn) => {
    //this.store.recordIndexScrollHeight()
    let noEditFields = []
    let detailid
    if (isPlanIn) {
      noEditFields = this.planInCanEditFields()
      detailid = this.store.summaryin[index].id
    } else {
      detailid = this.store.summaryout[index].id
    }
    let { canedit } = this.store
    this.store.detailId = record.id
    if (!detailid) {
      this.saveDetail(record).then(res => {
        if (res.api_status == 1) {
          detailid = res.plandetailid
          if (isPlanIn) {
            this.store.summaryin[index].id = detailid
          } else {
            this.store.summaryout[index].id = detailid
          }
          this.props.history.push({
            pathname: this.store.detailLayoutStore.path,
            search: `${detailid}&${3}&${this.store.type1}&${this.store.resourceid}&${canedit}&${noEditFields.join('^')}&${isPlanIn?'in':'out'}`

          })
        } else {
          Bubble.error(getLabel('508818', '接口调用失败！'), 3);
        }

      })
    } else {
      this.props.history.push({
        pathname: this.store.detailLayoutStore.path,
        search: `${detailid}&${3}&${this.store.type1}&${this.store.resourceid}&${canedit}&${noEditFields.join('^')}&${isPlanIn?'in':'out'}`
      })
    }

  }


  onSummaryInDelete = datas => {
        this.store.summaryin = datas;
  };

  onSummaryOutDelete = datas => {
        this.store.summaryout = datas;
  };
  onAdd = () => {
    //this.store.recordIndexScrollHeight()
    this.props.history.push({ pathname: this.store.newLayoutStore.path, search: 'summaryout' })
    // this.props.history.push(this.store.newLayoutStore.path)
  };
  //计划内的不能编辑的字段
  planInCanEditFields = () => {
    let { planmap, summarymap } = this.store
    let noEditFields = []
    if (planmap && summarymap && planmap.list && summarymap.list) {
      summarymap.list.map(s => {
        planmap.list.map(p => {
          if (s.fieldname == p.fieldname) {
            noEditFields.push(s.fieldname)
          }
        })
      })
    }

    return noEditFields
  }

  saveDetail = (data) => {
    let params = {
      operation: 'save_detail',
      resourceid: this.store.resourceid, dataType: 3,
      type1: this.store.type1,
      detailData: JSON.stringify([data])
    };
    return this.store.saveDetailView(params,false)
  }


  //单个删除
  singleOutDelete = () => {
    return (index) => {
      this.alertModal(() => {
        if (this.store.summaryout[index]) {
          this.store.summaryout.splice(index, 1)
        }
      }, getLabel('509113','确认删除此报告吗？') )
      
    }
  }
  singleInDelete = () => {
    return (index) => {
      this.alertModal(() => {
        if (this.store.summaryin[index]) {
          this.store.summaryin.splice(index, 1)
        }
      }, getLabel('509113','确认删除此报告吗？') )
      
    }
  }

  //查看明细
  getDetailViewFunc = (dataList, isPlanIn) => {
    let noEditFields = []
    if (isPlanIn) {
      noEditFields = this.planInCanEditFields()
    }
    let { canedit } = this.store
    return (index) => {
      //this.store.recordIndexScrollHeight()
      //如果没有id 要先保存 
      let detailid = dataList[index].id
      this.store.detailId = detailid
      if (!detailid) {
        this.saveDetail(dataList[index]).then(res => {
          if (res.api_status == 1) {
            dataList[index].id = res.plandetailid
            detailid = res.plandetailid
            this.props.history.push({
              pathname: this.store.detailLayoutStore.path,
              search: `${detailid}&${3}&${this.store.type1}&${this.store.resourceid}&${canedit}&${noEditFields.join('^')}&${isPlanIn?'in':'out'}`
            })
          } else {
            Bubble.error(getLabel('508818', '接口调用失败！'),);
          }

        })
      } else {
        this.props.history.push({
          pathname: this.store.detailLayoutStore.path,
          search: `${detailid}&${3}&${this.store.type1}&${this.store.resourceid}&${canedit}&${noEditFields.join('^')}&${isPlanIn?'in':'out'}`
        })
      }

    }
  }

  //创建任务
  addTask = (record, index, inOrOut) => {

    if (!record.id) {
      this.saveDetail(record).then(res => {
        inOrOut == 'summaryin' ? this.store.summaryin[index].id = res.plandetailid : this.store.summaryout[index].id = res.plandetailid
        this.store.addTask(record.name, res.plandetailid, record.begindate2 ? record.begindate2 : record.begindate1, record.enddate2 ? record.enddate2 : record.enddate1).then(res=>{
          if(res.api_status){
            this.openTaskDetail(res.taskId)
          }
        })
      })
    } else {
      this.store.addTask(record.name, record.id, record.begindate2 ? record.begindate2 : record.begindate1, record.enddate2 ? record.enddate2 : record.enddate1).then(res=>{
        if(res.api_status){
          this.openTaskDetail(res.taskId)
        }
      })
    }
  }

  openTaskDetail=(id)=>{
    this.props.history.push(`/taskHome/taskDetail/${id}`)
  }

  //新增一行数据
  addNew=(index)=>{
    //this.store.recordIndexScrollHeight()
    this.props.history.push({ pathname: this.store.newLayoutStore.path, search: 'summaryout&'+index })
  }

  //获取计划内下拉框
  getSummaryInDropList = () => {
    let { summaryin,canedit } = this.store
    let _ = this
    let drops = []
    drops.push({
      title: getLabel('382624', '查看明细'),
      func: _.getDetailViewFunc(summaryin, true)
    })
    canedit && drops.push({
      title: getLabel('16336', '创建任务'),
      func: (index) => {
        let record = summaryin[index]
        this.alertModal(() => {
          this.addTask(record, index, 'summaryin')
        }, getLabel('509023', '确定创建任务？'))
      }
    })
    return drops
  }

  //获取计划外下拉框
  getSummaryOutDropList = () => {
    let { summaryout, planlist, planmap, canedit,isshowplan } = this.store
    let _ = this
    let drops = []
    canedit && drops.push({
      title:getLabel('509025','新增一行数据'),
      func: (index) => {
        _.addNew(index+1)
      }
    })
    canedit && isshowplan!="0" && drops.push({
      title: getLabel('509024', '添加到工作计划'),
      func: (index) => {
        let record  = toJS(summaryout[index])
        delete record['id']
        if(planmap && planmap.list && planmap.list.length>0){
          planmap.list.map(p=>{
            record[p.fieldname] = record[p.fieldname]
          })
        }
        planlist.push(record)
        Bubble.success(getLabel('30700','操作成功'), 3);
      }
    })
    canedit && drops.push({
      title: getLabel('16336', '创建任务'),
      func: (index) => {
        let record = summaryout[index]
        this.alertModal(() => {
          this.addTask(record, index, 'summaryout')
        }, getLabel('509023', '确定创建任务？'))
      }
    })
    drops.push({
      title: getLabel('382624', '查看明细'),
      func: _.getDetailViewFunc(summaryout)
    })

    if (canedit) {
      drops.push({
        key:'delete',
        title: getLabel(91, '删除'),
        func: _.singleOutDelete()
      })
    }


    return drops
  }

  //alertModal
  alertModal = (onOk, title) => {
    alert(getLabel('386786', '信息确认'), title, [
      { text: getLabel(31129, '取消'), onPress: () => { } },
      {
        text: getLabel(826, '确定'),
        onPress: () => {
          if (onOk) {
            onOk()
          }
        },
      },
    ])
  }

}

export default Summary;
